package com.venue.hjt.venueclass.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import android.widget.Toast
import com.google.gson.Gson

import com.venue.hjt.venueclass.R
import com.venue.hjt.venueclass.adapter.VenueSignAdapter
import com.venue.hjt.venueclass.adapter.VenueSignFaceAdapter
import com.venue.hjt.venueclass.adapter.VenueSignSuccessAdapter
import com.venue.hjt.venueclass.bean.API
import com.venue.hjt.venueclass.bean.VenueBooKingDetaitBean
import com.venue.hjt.venueclass.db.CardDao
import com.venue.hjt.venueclass.utlis.*
import kotlinx.android.synthetic.main.activity_main2.*
import kotlinx.android.synthetic.main.activity_venue_order.*
import kotlinx.android.synthetic.main.activity_venue_sign.*
import okhttp3.Call
import java.lang.Exception


class VenueSignActivity : AppCompatActivity() {
    var tid=""
    var type=-1
    var adapter:VenueSignAdapter?=null
    var adapter1:VenueSignFaceAdapter?=null
    var adapterSuccess:VenueSignSuccessAdapter?=null
    val total=ArrayList<VenueBooKingDetaitBean.Total>()
    val faceerr=ArrayList<VenueBooKingDetaitBean.FaceErr>()
    val sign=ArrayList<VenueBooKingDetaitBean.Signin>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar!!.hide()
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        setContentView(R.layout.activity_venue_sign)
        receiver= SignReceiver()
        registerReceiver(receiver, filter())
        tid = intent.getStringExtra("id")
//        intent.putExtra("groupname",list[i].groupname)
//        intent.putExtra("time",list[i].time)
//        intent.putExtra("user_score",list[i].user_score)
        val groupname = intent.getStringExtra("groupname")
        val time = intent.getStringExtra("time")
        val user_score = intent.getStringExtra("user_score")
        val manager_score = intent.getStringExtra("manager_score")
        val booker = intent.getStringExtra("booker")
        type = intent.getIntExtra("type", -1)
        when (type) {
            0 -> tv_sign_type.text="签到中"
            1 -> tv_sign_type.text="未到签到时间"
            2 -> tv_sign_type.text="已结束"
        }
        if (user_score!="0"){
            tv_sign_p.text="已评价"
        }
        if (user_score!="0"&&manager_score!="0"){
            tv_sign_p.text="已评价"
        }
        tv_sign_name.text=groupname
        tv_sign_time.text="("+time+"场馆使用)"
        Log.e("ATG",API.VENUEBOOKINGDETAIL+Constant.SNO+"/"+tid);
        OkhttPost.Okget(API.VENUEBOOKINGDETAIL+Constant.SNO+"/"+tid,1,object : OkhttPost.Callback {
            override fun onError(call: Call?, e: Exception?, id: Int) {
            }
            override fun onResponse(response: String?, id: Int) {
                Log.e("ATG",response)
                val gson=Gson()
                val venue = gson.fromJson(response, VenueBooKingDetaitBean::class.java)
                if (venue.code==1){
                    total+=venue.data.total
                    faceerr+=venue.data.face_err
                    sign+=venue.data.signin
                    tv_noTo.text="未到"+total.size.toString()+"人"
                    tv_Face.text="人脸识别失败"+faceerr.size.toString()+"人"
                    tv_to.text="实到人数"+sign.size.toString()+"人"
                    adapter=VenueSignAdapter(this@VenueSignActivity,total,type,tid)
                    rl_noTo.adapter=adapter
                    adapter1=VenueSignFaceAdapter(this@VenueSignActivity,faceerr,type,tid)
                    rl_Face.adapter=adapter1
                    adapterSuccess=VenueSignSuccessAdapter(this@VenueSignActivity,sign)
                    rl_to.adapter=adapterSuccess
                    tv_sign_num.text= "应到"+(total.size+sign.size)+"人/已到"+sign.size+"人/未到"+total.size+"人"
                }
            }
        })
        ll_VenueY.setOnClickListener({
            if (type==2){
                if (i<5){
                    Toast.makeText(this@VenueSignActivity,"请稍后再点击",Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }else if (i<22){
                   i=22
                }
                val kingId = CardDao.queryVenueBooKingId(tid)
                val dialog=DialogUtlis()
                if (kingId.size!=0){
                    val manager_score1 = kingId[0].manager_score
                    val user_score1 = kingId[0].user_score
                    val typeuser = kingId[0].typeuser
                    val typemanager = kingId[0].typemanager
                    if (manager_score1!="0"&&user_score1!="0"){
                        Toast.makeText(this@VenueSignActivity,"当前已评价",Toast.LENGTH_LONG).show()
                    }else{
                        dialog.showDialog(this@VenueSignActivity,3,"刷卡后马上进行场馆评论",tid,groupname,"("+time+"场馆使用)","",
                                "应到"+(total.size+sign.size)+"人/已到"+sign.size+"人/未到"+total.size+"人",booker,user_score1,manager_score1,typeuser,typemanager)
                    }
                }
            }else{
                    Toast.makeText(this@VenueSignActivity,"已结束场馆才能评价",Toast.LENGTH_LONG).show()
            }
        })
        iv_sign_close1.setOnClickListener({
            i=1
        })
        Thread(Runnable {
            while (i > 0) {
                handler.sendEmptyMessage(1)
                if (i <= 0) {
                    break
                }
                try {
                    Thread.sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                i--
            }
            handler.sendEmptyMessage(2)
        }).start()
    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_HOME -> return true
            KeyEvent.KEYCODE_BACK -> return true
            KeyEvent.KEYCODE_CALL -> return true
            KeyEvent.KEYCODE_SYM -> return true
            KeyEvent.KEYCODE_VOLUME_DOWN -> return true
            KeyEvent.KEYCODE_VOLUME_UP -> return true
            KeyEvent.KEYCODE_STAR -> return true
        }
        return super.onKeyDown(keyCode, event)
    }
    internal var i = 80
    internal var handler: Handler = object : Handler() {
        override fun handleMessage(msg: android.os.Message) {
            if (msg.what == 1) {
//                tv_countdown.text = "还剩" + i + "关闭界面"
                tv_sign_countdown1.text="还剩" + i + "关闭界面"
            } else {
//                unregisterReceiver(receiver)
                this@VenueSignActivity.finish()
            }
        }
    }

    var receiver:SignReceiver?=null
    /**
     * 广播类
     */
    inner class SignReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when (action) {
                Constant.SIGN->{
                    if (i<0){
                        i=30
                    }
                    OkhttPost.Okget(API.VENUEBOOKINGDETAIL+Constant.SNO+"/"+tid,1,object : OkhttPost.Callback {
                        override fun onError(call: Call?, e: Exception?, id: Int) {
                        }

                        override fun onResponse(response: String?, id: Int) {
                            Log.e("ATG",response)
                            val gson=Gson()
                            val venue = gson.fromJson(response, VenueBooKingDetaitBean::class.java)
                            if (venue.code==1){
                                total.clear()
                                faceerr.clear()
                                sign.clear()
                                total+=venue.data.total
                                faceerr+=venue.data.face_err
                                sign+=venue.data.signin
                                tv_noTo.text="未到"+total.size.toString()+"人"
                                tv_Face.text="人脸识别失败"+faceerr.size.toString()+"人"
                                tv_to.text="实到人数"+sign.size.toString()+"人"
                                adapter!!.notifyDataSetChanged()
                                adapter1!!.notifyDataSetChanged()
                                adapterSuccess!!.notifyDataSetChanged()
                                tv_sign_num.text= "应到"+(total.size+sign.size)+"人/已到"+sign.size+"人/未到"+total.size+"人"
                            }
                        }
                    })
                }
            }
        }
    }
    override fun onDestroy() {
        unregisterReceiver(receiver)
        super.onDestroy()
    }
    /**
     * @return IntentFilter 广播
     */
    private fun filter(): IntentFilter {
        val filter = IntentFilter()
        filter.addAction(Constant.SIGN)
        return filter
    }
}